var wxpay = require('../../../utils/order_pay.js');
var app = getApp();
var ddapi = require("../../../utils/md5.js");
Page({
	data: {
    tabs: ["待付款(0)", "待使用(0)", "待评价(0)", "已完成(0)"],
		tabClass: ["", "", "", ""],
		stv: {
			windowWidth: 0,
			lineWidth: 0,
			offset: 0,
			tStart: false
		},
		tabType: {
			0: '1',
			1: '2',
			2: '3',
			3: '4',
		},
		statusType: {
			'1': "待支付",
			'2': "待使用",
			'3': "待评价",
			'4': "已完成",
		},
		activeTab: 0,
		loadingStatus: false,
	},
	onLoad: function (options) {
    let { tabs } = this.data;
    var res = wx.getSystemInfoSync()
    this.windowWidth = res.windowWidth;
    this.data.stv.lineWidth = this.windowWidth / this.data.tabs.length;
    this.data.stv.windowWidth = res.windowWidth;
    this.setData({ stv: this.data.stv })
    this.tabsCount = tabs.length;
    wx.setStorageSync('orderState', 1);
	},
	onShow: function () {
    var that = this
    var status = wx.getStorageSync('orderState');
    that.getOrderCount();
    that.getOrderList(status)
	},
  getOrderCount: function () {
    var that = this
    var service = 'User.GetOrderCount';
    var openid = wx.getStorageSync('openid');
    var user_id = wx.getStorageSync('user_id');
    var sign = ddapi.md5(openid + service + user_id);
    wx.request({
      url: app.globalData.apiUrl + '?service=User.GetOrderCount',
      header: {
        'Content-Type': 'json'
      },
      data: {
        sign: sign,
        open_id: openid,
        user_id: user_id
      },

      success: function (res) {
        console.log(res)
        if (res.data.data.code == 0) {
          var tabs = that.data.tabs;
          var info = res.data.data.info[0];
          console.log(info);
          if (info.one > 0) {
            tabs[0] = "待付款(" + info.one + ")"
          }
          if (info.tow > 0) {
            tabs[1] = "待使用(" + info.tow + ")"
          }
          if (info.three > 0) {
            tabs[2] = "待评价(" + info.three + ")"
          }
          if (info.fore > 0) {
            tabs[3] = "已完成(" + info.fore + ")"
          }
          that.setData({
            tabs: tabs,
          });
        }
      }
    })
  },
	getOrderList: function (type) {
    wx.setStorageSync('orderState', type);
    wx.showToast({
      title: '加载中',
      icon: 'loading'
    })
    var that = this;
		// setTimeout(function(){
      var open_id = wx.getStorageSync('openid');
      var order_type = type + '';
      var service = 'User.GetNewOrder';
      var user_id = wx.getStorageSync('user_id');
      var sign = ddapi.md5(open_id + order_type + service + user_id);
      console.log(open_id + order_type + service + user_id + sign)
      wx.request({
        url: app.globalData.apiUrl + '?service=User.GetNewOrder',
        header: {
          'Content-Type': 'json'
        },
        data: {
          sign: sign,
          user_id: user_id,
          open_id: open_id,
          order_type: order_type,
        },
        success: function(res)  {
          console.log(res);
          var result = res.data.data;
          if (result.code == 0) {
            var orderList = [];
            for (let i = 0; i < result.info.length; i++) {
              var line = result.info[i];
              var statusType = '';
              // if(line.status==5){
              //   line.statusStr = '已取消';
              // }else{
              //   line.status = type;
              //   line.statusStr = that.data.statusType[type];
              // }
              if (line.delive_type == 1){
                if (line.order_pid == 1) {
                  statusType = '待支付';
                }
                if (line.order_pid == 2 && line.order_hexiao == 1 && line.pinglun == 0) {
                  statusType = '待使用';
                }
                if (line.order_pid == 2 && line.order_hexiao == 2 && line.pinglun == 0) {
                  statusType = '待评价';
                }
                if (line.order_pid == 2 && line.pinglun == 1) {
                  statusType = '交易完成';
                }

                if (line.status == 5 && line.order_pid == 3) {
                  statusType = '已退款';
                }
             }
              if (line.delive_type == 2){
                if (line.status == 0) {
                  statusType = '待支付';
                }
                if (line.status == 1) {
                  statusType = '待接单';
                }
                if (line.status == 2) {
                  statusType = '待配送';
                }
                if (line.status == 3) {
                  statusType = '配送中';
                }
                if (line.status == 4 && line.pinglun != 1) {
                  statusType = '待评价';
                }
                if (line.status == 4 && line.pinglun == 1) {
                  statusType = '交易完成';
                }
                if (line.status == 5 && line.order_pid == 3) {
                  statusType = '已退款';
                }
             }
              line.statusStr = statusType;
              orderList.push(line);
            }
            wx.hideToast()
            that.setData({
              orderList: orderList
            });
          } else {
            wx.hideToast();
            that.setData({
              orderList: 'null',
            });
            return;
          }
        },
        complete: function (res) {
          console.log(res);
        },
      })
    // },2000)
	},
	orderDetail: function (e) {
		var orderId = e.currentTarget.dataset.id;
		var ordernum = e.currentTarget.dataset.ordernum;
		var tyep = e.currentTarget.dataset.type;
    var shop_id = e.currentTarget.dataset.shopid;
		if (tyep == 3){
		  wx.navigateTo({
        url: "/pages/ucenter/order-comment/index?id=" + orderId + "&shop_id=" + shop_id
		  })
		}else{
			wx.navigateTo({
        url: "/pages/ucenter/order-details/index?id=" + orderId + "&ordernum="+ordernum
			})
		}	
	},
  toPayTap: function (e) {
    var that = this;
    var client = 'wxa';
	  var cost = e.currentTarget.dataset.money;
	  var order_id = e.currentTarget.dataset.id;
	  var order_num = e.currentTarget.dataset.number;
	  var service = 'Pay.Index';
	  var type = 'wechat';
    var openid = wx.getStorageSync('openid');
    var user_id = wx.getStorageSync('user_id');
	  var sign = ddapi.md5(client + cost + openid + order_id + order_num + service + type + user_id);
	wx.request({
    url: app.globalData.apiUrl + '?service=Pay.Index',
		header: {
			'Content-Type': 'json'
		},
		data: {
			client: client,
			cost: cost,
			openid: openid,
			order_id: order_id,
			order_num: order_num,
			type: type,
			user_id: user_id,
			sign: sign,
		},
		success: function(res) {
			var result = res.data.data;
			if (result.code != 0) {
				wx.showModal({
					title: '失败',
					content: result.msg,
					showCancel: false
				})
				wx.hideToast();
				return;
			}
      wx.hideToast();
			wxpay.wxpay(app, cost, order_num, "/pages/ucenter/order-list/index");
		},
		complete: function(res) {
			console.log(res);
		},
	})
    // wx.request({
    //   url: 'https://ml002.zntech-china.com/' + app.globalData.subDomain + '/user/amount',
    //   header: {
    //     'Content-Type': 'json'
    //   },
    //   data: {
    //     token: wx.getStorageSync('token')
    //   },
    //   success: function (res) {
    //     if (res.data.code == 0) {
    //       // res.data.data.balance
    //       money = money - res.data.data.balance;
    //       if (res.data.data.score < needScore) {
    //         wx.showModal({
    //           title: '错误',
    //           content: '您的积分不足，无法支付',
    //           showCancel: false
    //         })
    //         return;
    //       }
    //       if (money <= 0) {
    //         // 直接使用余额支付
    //         wx.request({
    //           url: 'https://ml002.zntech-china.com/' + app.globalData.subDomain + '/order/pay',
    //           method: 'POST',
    //           header: {
    //             'content-type': 'application/x-www-form-urlencoded'
    //           },
    //           data: {
    //             token: wx.getStorageSync('token'),
    //             orderId: orderId
    //           },
    //           success: function (res2) {
    //             that.onShow();
    //           }
    //         })
    //       } else {
    //         wxpay.wxpay(app, money, orderId, "/pages/ucenter/order-list/index");
    //       }
    //     } else {
    //       wx.showModal({
    //         title: '错误',
    //         content: '无法获取用户资金信息',
    //         showCancel: false
    //       })
    //     }
    //   }
    // })
  },
  ////////
  handlerStart(e) {
    console.log('handlerStart')
    let { clientX, clientY } = e.touches[0];
    this.startX = clientX;
    this.tapStartX = clientX;
    this.tapStartY = clientY;
    this.data.stv.tStart = true;
    this.tapStartTime = e.timeStamp;
    this.setData({ stv: this.data.stv })
  },
  handlerMove(e) {
    console.log('handlerMove')
    let { clientX, clientY } = e.touches[0];
    let { stv } = this.data;
    let offsetX = this.startX - clientX;
    this.startX = clientX;
    stv.offset += offsetX;
    if (stv.offset <= 0) {
      stv.offset = 0;
    } else if (stv.offset >= stv.windowWidth * (this.tabsCount - 1)) {
      stv.offset = stv.windowWidth * (this.tabsCount - 1);
    }
    this.setData({ stv: stv });
  },
  handlerCancel(e) {

  },
  handlerEnd(e) {
    console.log('handlerEnd')
    let { clientX, clientY } = e.changedTouches[0];
    let endTime = e.timeStamp;
    let { tabs, stv, activeTab } = this.data;
    let { offset, windowWidth } = stv;
    //快速滑动
    if (endTime - this.tapStartTime <= 300) {
      console.log('快速滑动')
      //判断是否左右滑动(竖直方向滑动小于50)
      if (Math.abs(this.tapStartY - clientY) < 50) {
        //Y距离小于50 所以用户是左右滑动
        console.log('竖直滑动距离小于50')
        if (this.tapStartX - clientX > 5) {
          //向左滑动超过5个单位，activeTab增加
          console.log('向左滑动')
          if (activeTab < this.tabsCount - 1) {
            this.setData({ activeTab: ++activeTab })
          }
        } else if (clientX - this.tapStartX > 5) {
          //向右滑动超过5个单位，activeTab减少
          console.log('向右滑动')
          if (activeTab > 0) {
            this.setData({ activeTab: --activeTab })
          }
        }
        stv.offset = stv.windowWidth * activeTab;
      } else {
        //Y距离大于50 所以用户是上下滑动
        console.log('竖直滑动距离大于50')
        let page = Math.round(offset / windowWidth);
        if (activeTab != page) {
          this.setData({ activeTab: page })
        }
        stv.offset = stv.windowWidth * page;
      }
    } else {
      let page = Math.round(offset / windowWidth);
      if (activeTab != page) {
        this.setData({ activeTab: page })
      }
      stv.offset = stv.windowWidth * page;
    }
    stv.tStart = false;
    this.setData({ stv: this.data.stv })
  },
  	////////
  	_updateSelectedPage(page) {
	  	console.log('_updateSelectedPage')
	  	let { tabs, stv, activeTab } = this.data;
	  	activeTab = page;
	  	this.setData({ activeTab: activeTab })
	  	stv.offset = stv.windowWidth * activeTab;
	  	this.setData({ stv: this.data.stv })
  	},
  	handlerTabTap(e) {
  		this._updateSelectedPage(e.currentTarget.dataset.index);
	  	this.getOrderList(this.data.tabType[e.currentTarget.dataset.index]);
  	},
  //事件处理函数
  swiperchange: function (e) {
    console.log('swiperCurrent',e.detail.current)
    let { tabs, stv, activeTab } = this.data;
    activeTab = e.detail.current;
    this.setData({ activeTab: activeTab })
    stv.offset = stv.windowWidth * activeTab;
    this.setData({ stv: this.data.stv })
  },
  toIndexPage: function () {
    wx.switchTab({
      url: "/pages/classification/index"
    });
  },
  showQr:function(e){
    var order_num = e.currentTarget.dataset.num
    wx.navigateTo({
      url: '/pages/ucenter/hexiao/hexiao?order_num='+order_num, 
    })
  }
})